<?php
namespace Admin\Controller;

use Base\Controller\AdminBaseController;

class UserController extends AdminBaseController {

	protected $userModel;
    protected $userRoleModel;

	public function _initialize() {
		parent::_initialize();
		
		$this->userModel = D("Admin/User");
        $this->userRoleModel = D("Admin/UserRole");
	}
	
	/******************************** JSON *********************************/
	/** 添加信息 */
	public function save() {
		$userJson = file_get_contents('php://input');
		$user = json_decode($userJson, true);
		
		// 检查用户名是否重复
		$oldUser = $this->userModel->where(array("username" => $user['username']))->find();
		if ($oldUser) {
			$data['code'] = 499;
			$data['msg'] = '用户名重复，添加失败！';
			$this->ajaxReturn($data);
		}
		
		// setting
		$user['password'] = sf_xcms_password('xcms');
		$user['add_time'] = Date('Y-m-d H:i:s');
		$user['update_time'] = Date('Y-m-d H:i:s');

		// 执行添加
		$result = $this->userModel->data($user)->add();
		if (!$result) {
			$data['code'] = 499;
			$data['msg'] = '添加失败！';
			$this->ajaxReturn($data);
		}

		$newUser = $this->userModel->where(array("id" => $result))->find();
			
		$data['code'] = 0;
		$data['msg'] = '添加成功！';
		$data['obj'] = $newUser;
		$this->ajaxReturn($data);
	}
	 
	/** 查看某信息 */
	public function find() {
		$id = $_GET['id'];
		
		$user = $this->userModel->where(array("id" => $id))->find();
		if (!$user) {
			$data['code'] = 499;
			$data['msg'] = '未找到目标！';
			$this->ajaxReturn($data);
		}
		
		$roleNames = $this->userRoleModel
				->join("__ROLE__ ON __USER_ROLE__.role_id = __ROLE__.id")
				->where(array("user_id" => $id))
				->getField('name', true);
// 		$sql = "select r.* from __USER_ROLE__ ur, __ROLE__ r
// 							where ur.role_id = r.id
// 							and ur.user_id = " . $id;
// 		$roleNames = M()->query($sql);

		$user['roleNames'] = $roleNames;
		
	    $data['code'] = 0;
	    $data['msg'] = 'OK';
	    $data['obj'] = $user;
	    $this->ajaxReturn($data);
	}

	/** 查看所有列表 */
	public function dataList() {
		$_GET['notEqualMap'] = ['status' => -1];
		$dataList = $this->userModel->dataList($_GET);

		// add role for user
		$rows = [];
		foreach ($dataList['rows'] as $v) {
			$userId = $v['id'];
			$v['roleNames'] = $this->userRoleModel
					->join("__ROLE__ ON __USER_ROLE__.role_id = __ROLE__.id")
					->where(array("user_id" => $userId))
					->getField('name', true);
			$rows[] = $v;
		}
		$dataList['rows'] = $rows;
		
	    $this->ajaxReturn($dataList);
	}

	/** 修改某信息 */
	public function update() {
		$id = $_GET['id'];
		$userJson = file_get_contents('php://input');
		$user = json_decode($userJson, true);

		// update
		$user['url'] = '';											// update reset
		$user['status'] = 0;										// update reset
		$user['update_time'] = date("Y-m-d H:i:s");
		
		// 执行更新
		$result = $this->userModel->where(array("id" => $id))->save($user);
		if (false === $result) {
			$data['code'] = 499;
			$data['msg'] = '编辑失败！';
			$this->ajaxReturn($data);
		}

		$updatedUser = $this->userModel->where(array("id" => $id))->find();
			
		$data['code'] = 0;
		$data['msg'] = '编辑成功！';
		$data['obj'] = $updatedUser;
		$this->ajaxReturn($data);
	}

	/** 审核 */
	public function audit() {
		$id = $_GET['id'];
		$status = $_GET['status'];
		
		$user = $this->userModel->where(array("id" => $id))->find();
		if (!$user) {
			$data['code'] = 499;
			$data['msg'] = '未找到目标！';
			$this->ajaxReturn($data);
		}
		
		// 更新status & update
		$user['status'] = $status;
		$user['update_time'] = date("Y-m-d H:i:s");
		
		// 执行更新
		$result = $this->userModel->where(array("id" => $id))->save($user);
		if (false === $result) {
			$data['code'] = 499;
			$data['msg'] = '审核失败！';
			$this->ajaxReturn($data);
		}

		$data['code'] = 0;
		$data['msg'] = '审核完成！';
		$data['obj'] = $user;
		$this->ajaxReturn($data);
	}
	
	/** 删除某信息（禁用） */
	public function delete() {
		$id = $_GET['id'];
		
		$user = $this->userModel->where(array("id" => $id))->find();
		if (!$user) {
			$data['code'] = 499;
			$data['msg'] = '未找到目标！';
			$this->ajaxReturn($data);
		}

		////// delete (更新status & update)
		$user['status'] = -1;
		$user['update_time'] = date("Y-m-d H:i:s");

		$result = $this->userModel->where(array("id" => $id))->save($user);
		if (false === $result) {
			$data['code'] = 499;
			$data['msg'] = '删除失败！';
			$this->ajaxReturn($data);
		}
			
		$data['code'] = 0;
		$data['msg'] = '删除成功！';
		$this->ajaxReturn($data);
	}

	/** 为某分配role */
	public function addRoles() {
		$id = $_GET['id'];
		$resIdListJson = file_get_contents('php://input');
		$resIdList = json_decode($resIdListJson, true);
		
		// remove all menus
		$this->userRoleModel->where(array("user_id" => $id))->delete();
		
		// add new menus
		foreach ($resIdList as $v) {
			$this->userRoleModel->add(array("user_id" => $id, "role_id" => $v));
		}

		$updatedUser = $this->userModel->where(array("id" => $id))->find();
		
		$data['code'] = 0;
		$data['msg'] = '编辑成功！';
		$data['obj'] = $updatedUser;
		$this->ajaxReturn($data);
	}

	/******************************** HTML *********************************/
	/** index */
    public function index() {
		$this->display(':user');
		return;
	}
	
}